package com.s4j.core.manager.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.s4j.core.common.MyDateUtils;
import com.s4j.core.common.StringUtils;
import com.s4j.core.datagrid.DatagridPaging;
import com.s4j.core.hibernate.CommonDao;
import com.s4j.core.manager.model.SysPerson;

@Service
public class SysPersonService {
	
//	private static Logger log = Logger.getLogger(ManagerAction.class);
	
	@Resource
	private CommonDao dao;

	public DatagridPaging findByPaging(Integer page, Integer rows, Map<String, Object> condition) {
		List<Object> params = new ArrayList<Object>();
		
		StringBuffer countHql = new StringBuffer();
		countHql.append(" from SysPerson sp ");
		
		StringBuffer columnHql = new StringBuffer();
		columnHql.append("from SysPerson sp ");
		
		StringBuffer whereHql = new StringBuffer();
		whereHql.append(" where 1 = 1");
		if(condition.containsKey("personNo")) {
			whereHql.append(" and sp.personNo like ? ");
			params.add("%" + condition.get("personNo") + "%");
		}
		if(condition.containsKey("personName")) {
			whereHql.append(" and sp.personName like ? ");
			params.add("%" + condition.get("personName") + "%");
		}
		
		countHql = countHql.append(whereHql);
		columnHql = columnHql.append(whereHql);
		
		DatagridPaging persons = dao.findByHQLPaging(countHql.toString(), columnHql.toString(), page, rows, params);
		return persons;
	}

	public SysPerson get(Long personId) {
		return (SysPerson)dao.get(SysPerson.class, personId);
	}

	public Long insert(SysPerson person) {
		person.setCreateTime(MyDateUtils.getCurDateTime());
		return (Long)dao.save(person);
	}

	public void update(SysPerson person) {
		dao.update(person);
	}
	
	public void remove(String personIds) {
		String[] idArr = personIds.split(",");
		for(int i=0; i<idArr.length; i++) {
			String personId = idArr[i];
			if(StringUtils.isNullOrBlank(personId)) {
				continue;
			}
			SysPerson person = dao.get(SysPerson.class, new Long(personId));
			if(person.getUsers().size() > 0) {
				throw new RuntimeException(person.getPersonName()+" 已绑定用户，不能删除。");
			}
			dao.remove(SysPerson.class, new Long(personId));
		}
	}
}
